/* eslint-disable react-native/no-inline-styles */
/* eslint-disable react/no-unstable-nested-components */
import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
} from 'react-native';
import TabView, { TabItem } from './components/TabView';
import { SafeAreaView } from 'react-native-safe-area-context';

// ==================== 示例1: 基础用法 ====================
const BasicExample: React.FC = () => {
  // 简单的页面内容组件
  const Page = ({ title, color }: { title: string; color: string }) => (
    <View style={[styles.pageContent, { backgroundColor: color }]}>
      <Text style={styles.pageTitle}>{title}</Text>
      <Text style={styles.pageText}>这是一个简单的页面内容</Text>
      <Text style={styles.pageText}>可以左右滑动切换</Text>
    </View>
  );

  const tabs: TabItem[] = [
    {
      key: 'tab1',
      label: '首页',
      renderContent: () => <Page title="首页" color="#fff3e0" />,
    },
    {
      key: 'tab2',
      label: '消息',
      badge: 5, // 数字徽章
      renderContent: () => <Page title="消息" color="#e8f5e9" />,
    },
    {
      key: 'tab3',
      label: '我的',
      renderContent: () => <Page title="我的" color="#e3f2fd" />,
    },
  ];

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例1: 基础用法</Text>
      <TabView tabs={tabs} tabBarPosition="top" />
    </View>
  );
};

// ==================== 示例2: 自定义标签 ====================
const CustomLabelExample: React.FC = () => {
  // 自定义标签组件
  const CustomLabel = ({
    icon,
    text,
    active,
  }: {
    icon: string;
    text: string;
    active: boolean;
  }) => (
    <View style={styles.customLabel}>
      <Text style={[styles.customIcon, active && styles.customIconActive]}>
        {icon}
      </Text>
      <Text style={[styles.customText, active && styles.customTextActive]}>
        {text}
      </Text>
    </View>
  );

  // 带滚动内容的页面
  const ScrollablePage = ({
    title,
    emoji,
  }: {
    title: string;
    emoji: string;
  }) => (
    <ScrollView style={styles.scrollablePage}>
      <Text style={styles.pageTitle}>
        {emoji} {title}
      </Text>
      {Array.from({ length: 20 }, (_, i) => (
        <View key={i} style={styles.listItem}>
          <Text style={styles.listItemText}>
            列表项 {i + 1} - 这是一个可滚动的内容区域
          </Text>
        </View>
      ))}
    </ScrollView>
  );

  const tabs: TabItem[] = [
    {
      key: 'home',
      renderLabel: active => (
        <CustomLabel icon="🏠" text="首页" active={active} />
      ),
      renderContent: () => <ScrollablePage title="首页" emoji="🏠" />,
    },
    {
      key: 'discover',
      renderLabel: active => (
        <CustomLabel icon="🔍" text="发现" active={active} />
      ),
      badge: true, // 红点
      renderContent: () => <ScrollablePage title="发现" emoji="🔍" />,
    },
    {
      key: 'notification',
      renderLabel: active => (
        <CustomLabel icon="🔔" text="通知" active={active} />
      ),
      badge: 99, // 数字徽章
      renderContent: () => <ScrollablePage title="通知" emoji="🔔" />,
    },
    {
      key: 'profile',
      renderLabel: active => (
        <CustomLabel icon="👤" text="我的" active={active} />
      ),
      renderContent: () => <ScrollablePage title="个人中心" emoji="👤" />,
    },
  ];

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例2: 自定义标签（图标+文字）</Text>
      <TabView
        tabs={tabs}
        tabBarPosition="top"
        onIndexChange={index => console.log('切换到:', index)}
      />
    </View>
  );
};

// ==================== 示例3: 多个Tab（测试滚动和懒加载） ====================
const ManyTabsExample: React.FC = () => {
  // 懒加载页面：只在首次显示时加载
  const LazyPage = ({ index }: { index: number }) => {
    const [loadTime] = React.useState(() => new Date().toLocaleTimeString());

    return (
      <View style={styles.pageContent}>
        <Text style={styles.pageTitle}>页面 {index + 1}</Text>
        <Text style={styles.pageText}>这是一个懒加载的页面</Text>
        <Text style={styles.pageText}>加载时间: {loadTime}</Text>
        <Text style={[styles.pageText, styles.hintText]}>
          💡 切换到其他页面再回来，时间不会改变
        </Text>
        <Text style={[styles.pageText, styles.hintText]}>
          这证明页面状态被保留了
        </Text>
      </View>
    );
  };

  const tabs: TabItem[] = Array.from({ length: 15 }, (_, i) => ({
    key: `tab${i}`,
    label: `Tab ${i + 1}`,
    badge: i === 3 ? 10 : i === 7 ? true : undefined,
    renderContent: () => <LazyPage index={i} />,
  }));

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例3: 多个Tab（懒加载）</Text>
      <TabView
        tabs={tabs}
        tabBarPosition="top"
        lazy={true} // 开启懒加载
        initialIndex={0}
      />
    </View>
  );
};

// ==================== 示例4: 底部Tab栏 ====================
const BottomTabExample: React.FC = () => {
  // 带交互的页面
  const InteractivePage = ({
    title,
    color,
  }: {
    title: string;
    color: string;
  }) => {
    const [count, setCount] = React.useState(0);

    return (
      <View style={[styles.pageContent, { backgroundColor: color }]}>
        <Text style={styles.pageTitle}>{title}</Text>
        <Text style={styles.counterText}>计数器: {count}</Text>
        <TouchableOpacity
          style={styles.button}
          onPress={() => setCount(count + 1)}
        >
          <Text style={styles.buttonText}>点击 +1</Text>
        </TouchableOpacity>
        <Text style={[styles.pageText, styles.hintText]}>
          💡 切换Tab后再回来，计数器状态会保留
        </Text>
      </View>
    );
  };

  const tabs: TabItem[] = [
    {
      key: 'home',
      label: '🏠 首页',
      renderContent: () => <InteractivePage title="首页" color="#fff3e0" />,
    },
    {
      key: 'message',
      label: '💬 消息',
      badge: 3,
      renderContent: () => <InteractivePage title="消息" color="#e8f5e9" />,
    },
    {
      key: 'add',
      label: '➕ 发布',
      renderContent: () => <InteractivePage title="发布" color="#fce4ec" />,
    },
    {
      key: 'explore',
      label: '🔍 发现',
      renderContent: () => <InteractivePage title="发现" color="#e1f5fe" />,
    },
    {
      key: 'profile',
      label: '👤 我的',
      renderContent: () => <InteractivePage title="我的" color="#f3e5f5" />,
    },
  ];

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例4: 底部Tab栏</Text>
      <TabView tabs={tabs} tabBarPosition="bottom" />
    </View>
  );
};

// ==================== 示例5: 禁用滑动 ====================
const DisabledSwipeExample: React.FC = () => {
  const Page = ({ title }: { title: string }) => (
    <View style={styles.pageContent}>
      <Text style={styles.pageTitle}>{title}</Text>
      <Text style={[styles.pageText, styles.hintText]}>
        ⚠️ 手势滑动已禁用，只能通过点击Tab切换
      </Text>
    </View>
  );

  const tabs: TabItem[] = [
    {
      key: 'tab1',
      label: 'Tab 1',
      renderContent: () => <Page title="页面 1" />,
    },
    {
      key: 'tab2',
      label: 'Tab 2',
      renderContent: () => <Page title="页面 2" />,
    },
    {
      key: 'tab3',
      label: 'Tab 3',
      disabled: true, // 禁用的Tab
      renderContent: () => <Page title="页面 3（禁用）" />,
    },
    {
      key: 'tab4',
      label: 'Tab 4',
      renderContent: () => <Page title="页面 4" />,
    },
  ];

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例5: 禁用滑动 & 禁用Tab</Text>
      <TabView tabs={tabs} tabBarPosition="top" swipeEnabled={false} />
    </View>
  );
};

// ==================== 示例6: 自定义样式 ====================
const CustomStyleExample: React.FC = () => {
  const Page = ({ title, color }: { title: string; color: string }) => (
    <View style={[styles.pageContent, { backgroundColor: color }]}>
      <Text style={styles.pageTitle}>{title}</Text>
    </View>
  );

  const tabs: TabItem[] = [
    {
      key: 'tab1',
      label: '精选',
      badge: 'NEW',
      renderContent: () => <Page title="精选" color="#fff8e1" />,
    },
    {
      key: 'tab2',
      label: '热门',
      badge: 99,
      renderContent: () => <Page title="热门" color="#ffe0b2" />,
    },
    {
      key: 'tab3',
      label: '关注',
      renderContent: () => <Page title="关注" color="#ffccbc" />,
    },
  ];

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例6: 自定义样式</Text>
      <TabView
        tabs={tabs}
        tabBarPosition="top"
        tabBarBackgroundColor="#ff6f00"
        tabBarStyle={styles.customTabBar}
        tabItemStyle={styles.customTabItem}
        tabItemActiveStyle={styles.customTabItemActive}
        tabLabelStyle={styles.customTabLabel}
        tabLabelActiveStyle={styles.customTabLabelActive}
        badgeStyle={styles.customBadge}
      />
    </View>
  );
};

const UnreadCountLabel: React.FC<{}> = ({}) => {
  // 不使用props的方式来更新未读数，可以降低cpu占用率
  const [unreadCount, setUnreadCount] = React.useState(0);
  React.useEffect(() => {
    const interval = setInterval(() => {
      setUnreadCount(prev => prev + 1);
    }, 100);
    return () => clearInterval(interval);
  }, []);
  return (
    <Text style={[styles.customTabLabel, { width: 40 }]}>{unreadCount}</Text>
  );
};

// ==================== 示例7: 每秒更新未读消息数 ====================
const UpdateUnreadCountExample: React.FC = () => {
  // const [unreadCount, setUnreadCount] = React.useState(0);
  // 简单的页面内容组件
  const Page = ({ title, color }: { title: string; color: string }) => (
    <View style={[styles.pageContent, { backgroundColor: color }]}>
      <Text style={styles.pageTitle}>{title}</Text>
      <Text style={styles.pageText}>这是一个简单的页面内容</Text>
      <Text style={styles.pageText}>可以左右滑动切换</Text>
    </View>
  );

  // React.useEffect(() => {
  //   const interval = setInterval(() => {
  //     setUnreadCount(prev => prev + 1);
  //   }, 100);
  //   return () => clearInterval(interval);
  // }, []);

  const tabs: TabItem[] = [
    {
      key: 'tab1',
      label: '首页',
      renderLabel: () => <UnreadCountLabel />,
      renderContent: () => <Page title="首页" color="#fff3e0" />,
    },
    {
      key: 'tab2',
      label: '消息',
      // badge: unreadCount, // 数字徽章
      renderContent: () => <Page title="消息" color="#e8f5e9" />,
    },
    {
      key: 'tab3',
      label: '我的',
      renderContent: () => <Page title="我的" color="#e3f2fd" />,
    },
  ];

  return (
    <View style={styles.exampleContainer}>
      <Text style={styles.exampleTitle}>示例1: 基础用法</Text>
      <TabView tabs={tabs} tabBarPosition="top" />
    </View>
  );
};

// ==================== 主入口 ====================
const TestTabPage: React.FC = () => {
  return (
    <SafeAreaView style={styles.container}>
      <ScrollView style={styles.scrollContainer}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>TabView 组件示例</Text>
          <Text style={styles.headerSubtitle}>React Native 自定义Tab组件</Text>
        </View>

        <BasicExample />
        <CustomLabelExample />
        <ManyTabsExample />
        <BottomTabExample />
        <DisabledSwipeExample />
        <CustomStyleExample />
        <UpdateUnreadCountExample />

        <View style={styles.footer}>
          <Text style={styles.footerText}>
            ✨ 所有示例均使用 React Native 内置组件实现，无需第三方库
          </Text>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

// ==================== 样式定义 ====================
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  scrollContainer: {
    flex: 1,
  },
  header: {
    padding: 20,
    backgroundColor: '#ffffff',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  headerTitle: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#333333',
    marginBottom: 4,
  },
  headerSubtitle: {
    fontSize: 14,
    color: '#666666',
  },
  exampleContainer: {
    marginTop: 20,
    backgroundColor: '#ffffff',
    borderRadius: 8,
    marginHorizontal: 16,
    overflow: 'hidden',
    height: 400, // 固定高度，便于查看
  },
  exampleTitle: {
    fontSize: 16,
    fontWeight: '600',
    color: '#333333',
    padding: 12,
    backgroundColor: '#f9f9f9',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  // 页面内容样式
  pageContent: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  pageTitle: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#333333',
    marginBottom: 16,
  },
  pageText: {
    fontSize: 16,
    color: '#666666',
    marginTop: 8,
    textAlign: 'center',
  },
  hintText: {
    fontSize: 14,
    color: '#999999',
    fontStyle: 'italic',
    marginTop: 16,
  },
  // 自定义标签样式
  customLabel: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
  },
  customIcon: {
    fontSize: 18,
    opacity: 0.6,
  },
  customIconActive: {
    opacity: 1,
  },
  customText: {
    fontSize: 14,
    color: '#666666',
  },
  customTextActive: {
    color: '#1976d2',
    fontWeight: '600',
  },
  // 可滚动页面样式
  scrollablePage: {
    flex: 1,
    padding: 16,
  },
  listItem: {
    padding: 16,
    backgroundColor: '#f5f5f5',
    borderRadius: 8,
    marginBottom: 8,
  },
  listItemText: {
    fontSize: 14,
    color: '#333333',
  },
  // 交互页面样式
  counterText: {
    fontSize: 48,
    fontWeight: 'bold',
    color: '#1976d2',
    marginVertical: 20,
  },
  button: {
    backgroundColor: '#1976d2',
    paddingHorizontal: 32,
    paddingVertical: 12,
    borderRadius: 24,
    marginTop: 16,
  },
  buttonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: '600',
  },
  // 自定义样式示例
  customTabBar: {
    height: 56,
    elevation: 4,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
  },
  customTabItem: {
    height: 56,
    paddingHorizontal: 20,
  },
  customTabItemActive: {
    backgroundColor: '#ff8f00',
  },
  customTabLabel: {
    fontSize: 16,
    color: '#ffffff',
    fontWeight: '500',
  },
  customTabLabelActive: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 17,
  },
  customBadge: {
    backgroundColor: '#ffffff',
    top: 8,
    right: 12,
  },
  // 页脚
  footer: {
    padding: 20,
    alignItems: 'center',
    marginTop: 20,
    marginBottom: 40,
  },
  footerText: {
    fontSize: 13,
    color: '#999999',
    textAlign: 'center',
  },
});

export default TestTabPage;
